package com.cuit.zuke.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.zuke.common.exception.GlobalException;
import com.cuit.zuke.common.util.Constant;
import com.cuit.zuke.common.util.PageUtil;
import com.cuit.zuke.system.dao.SysRoleDao;
import com.cuit.zuke.system.entity.SysRoleEntity;
import com.cuit.zuke.system.service.SysAdminRoleService;
import com.cuit.zuke.system.service.SysAdminService;
import com.cuit.zuke.system.service.SysRoleMenuService;
import com.cuit.zuke.system.service.SysRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @program: zuke
 * @description: 管理员与角色对应关系服务实现类
 * @author: KamTang
 * @create: 2022-04-26 14:12
 **/
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRoleEntity> implements SysRoleService {

    @Autowired
    private SysAdminService adminService;

    @Lazy
    @Autowired
    private SysRoleMenuService roleMenuService;

    @Autowired
    private SysAdminRoleService adminRoleService;

    /**
     * 根据用户ID，获取角色ID列表
     *
     * @param userId 管理员id
     * @return 角色ID列表
     */
    @Override
    public List<Long> queryRoleIdList(Long userId) {
        return this.baseMapper.queryRoleIdList(userId);
    }


    /**
     * 分页查询
     *
     * @param params 传入参数
     * @return PageUtil
     */
    @Override
    public PageUtil queryPage(Map<String, Object> params) {
        String roleName = (String)params.get("roleName");
        Long createUserId = (Long)params.get("createUserId");
        long currentPage = Long.parseLong((String) params.get("currentPage"));
        long pageSize = Long.parseLong((String) params.get("pageSize"));
        QueryWrapper<SysRoleEntity> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(roleName), "role_name", roleName)
                .eq(createUserId!=null, "create_user_id", createUserId);
        Page<SysRoleEntity> page = new Page<>(currentPage, pageSize);
        IPage<SysRoleEntity> iPage = this.baseMapper.selectPage(page, wrapper);
        return new PageUtil(iPage);
    }

    /**
     * 添加角色
     *
     * @param role 角色
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRole(SysRoleEntity role) {
        this.save(role);
        // 检查是否越权
        checkPerms(role);
        // 保存角色与菜单的关系
        roleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    /**
     * 更新
     *
     * @param role 角色实体类
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRoleEntity role) {
        this.updateById(role);
        //检查权限是否越权
        checkPerms(role);

        //更新角色与菜单关系
        roleMenuService.saveOrUpdate(role.getRoleId(), role.getMenuIdList());
    }

    /**
     * 删除
     *
     * @param roleIds 角色ID列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] roleIds) {
        //删除角色
        this.removeByIds(Arrays.asList(roleIds));

        //删除角色与菜单关联
        roleMenuService.removeByIds(Arrays.asList(roleIds));

        //删除角色与用户关联
        adminRoleService.removeByIds(Arrays.asList(roleIds));
    }

    @Override
    public SysRoleEntity getRoleInfoById(Long id) {
        SysRoleEntity roleEntity = this.baseMapper.selectById(id);
        List<Long> menuIdList = roleMenuService.queryMenuIdList(id);
        roleEntity.setMenuIdList(menuIdList);
        return roleEntity;
    }

    @Override
    public List<SysRoleEntity> getRoleInfoByUserId(Long userId) {
        return this.baseMapper.getRoleInfoByUserId(userId);
    }

    /**
     * 检查权限是否越权
     */
    private void checkPerms(SysRoleEntity role){
        //如果不是超级管理员，则需要判断角色的权限是否超过自己的权限
        if(role.getCreateUserId() == Constant.SUPER_ADMIN){
            return ;
        }

        //查询用户所拥有的菜单列表
        List<Long> menuIdList = adminService.getMenuIdByUserId(role.getCreateUserId());

        //判断是否越权
        if(!menuIdList.containsAll(role.getMenuIdList())){
            throw new GlobalException("新增角色的权限，已超出你的权限范围");
        }
    }
}
